// 获取sequelize 实例
const { sequelize } = require("../model/connect");
// 传入数据模型函数,并的到 User 模型
const { Area } = require("../model/models")(sequelize);

// 获取全部的省
const getProvinces = async (ctx) => {
    try {
        const provinces = await Area.findAll({
            attributes: ["code", "value"],
            where: { parentCode: null },
        });
        ctx.status = 200;
        ctx.body = {
            code: 10000,
            message: "获取省份列表成功",
            data: provinces,
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 10005,
            message: error.message,
        };
    }
};

// 获取某个省份的市
const getCitiesByProvince = async (ctx) => {
    try {
        // 获取省份code
        const { provinceCode } = ctx.params;
        const cities = await Area.findAll({
            attributes: ["code", "value", "parentCode"],
            where: { parentCode: provinceCode },
        });
        ctx.status = 200;
        ctx.body = {
            code: 10000,
            message: "获取市列表成功",
            data: cities,
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 10005,
            message: error.message,
        };
    }
};
// 获取某个市的下的区/县
const getAreasByCity = async (ctx) => {
    try {
        // 获取市code
        const { cityCode } = ctx.params;
        const areas = await Area.findAll({
            attributes: ["code", "value", "parentCode"],
            where: { parentCode: cityCode },
        });
        ctx.status = 200;
        ctx.body = {
            code: 10000,
            message: "获取地区列表成功",
            data: areas,
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            code: 10005,
            message: error.message,
        };
    }
};
module.exports = {
    getProvinces,
    getCitiesByProvince,
    getAreasByCity,
};
